const Websocket = require('websocket').server;
const http = require('http');
const fs = require('fs');
const jwt = require('jsonwebtoken');
const token = jwt.sign({
    exp: Math.floor(Date.now() / 1000) + (60 * 60),
    data: 'foobar'
}, 'secret');
// console.log(token);
const httpServer = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-type': 'text/html', 'charset': 'utf-8' });
    const urlObj = new URL(`${req.url}`, 'http://localhost:3000')
    let obj = {}
    for (const pair of urlObj.searchParams.entries()) {
        obj[pair[0]] = pair[1]
    }
    if (urlObj.pathname == '/login') {


        fs.readFile('./test.json', 'utf-8', (err, data) => {
            fs.readFile('./login.json', 'utf-8', (err, data) => {
                const loginArr = JSON.parse(data)
                loginArr.push(obj.admin)
                const newArr = [...new Set(loginArr)]
                const str = JSON.stringify(newArr)
                // console.log(str);
                fs.writeFile('./login.json', str, 'utf-8', function (err, data) {
                })
            })
            console.log('有人请求服务器了');
            if (!data) {
                let msgObj = {
                    "msg": '数据库中不存在数据'
                }
                res.end(JSON.stringify(msgObj))
            } else {
                arrList = JSON.parse(data);
                const arr = arrList.map((value, index, array) => {
                    if (obj.admin === value.admin && obj.password === value.password1 && obj.password === value.password2) {
                        return value.admin
                    }
                })
                if (arr.includes(obj.admin)) {
                    fs.readFile('./login.json', 'utf-8', (err, data) => {
                        if (data.includes(obj.admin)) {
                            let msg = `{"code":3,"message":"登录成功","Token":"${token}"}`;
                            res.end(msg);
                        } else {
                            let msg = `{"code":0,"message":"登录成功","Token":"${token}"}`;
                            res.end(msg);
                        }

                    })
                    // console.log(num);

                } else {
                    let msg1 = `{"code":1,"message":"登录失败"}`;
                    res.end(msg1)
                }
                // console.log(arr);
            }
        })
    }

    if (urlObj.pathname == '/enroll') {
        fs.readFile('./test.json', 'utf-8', (err, data) => {
            // console.log(obj);
            arrList = JSON.parse(data)
            const arr = arrList.map((value, index, array) => {
                return value.admin
            })
            if (arr.includes(obj.admin)) {
                let msg = `{"code":0,"message":"用户名已存在"}`;
                res.end(msg);
            } else if (obj.password1 != obj.password2) {
                let msg1 = `{"code":1,"message":"两次输入密码不一致"}`
                res.end(msg1);
            } else {
                let msg2 = `{"code":2,"message":"注册成功请登录"}`
                res.end(msg2);
                arrList.push(obj)
                const str = JSON.stringify(arrList)
                console.log(str);
                fs.writeFile('./test.json', str, 'utf-8', function (err, data) {
                    res.end(str)
                })
            }
        })
    }
    if (urlObj.pathname == '/out') {
        fs.readFile('./login.json', 'utf-8', (err, data) => {
            const arr = JSON.parse(data)
            const { admin: item } = obj
            if (data.includes(item)) {
                const result = [];
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i] != item) {
                        result.push(arr[i]);
                    }
                }
                const str = JSON.stringify(result)
                // console.log(str);
                fs.writeFile('./login.json', str, 'utf-8', function (err, data) {
                })
            }
        })
    }
}).listen(3000, () => {
    console.log('server.start...');
})

const wsServer = new Websocket({
    httpServer: httpServer,
    autoAcceptConnections: false
})

const conArr = []

wsServer.on('request', function (request) {
    const connection = request.accept()
    conArr.push(connection)
    connection.on('message', function (data) {
        const data1 = JSON.parse(data.utf8Data)
        console.log(data1);
        const { text } = data1
        const { user } = data1
        console.log('!!!', text);
        console.log('!!!', user);
        for (let i = 0; i < conArr.length; i++) {
            console.log('$$$', conArr.length);
            const str = `{"msg":"${text}","len":"${user}"}`
            conArr[i].send(str)
        }
    })
})